<?php
/*
 * This file is part of EC-CUBE
 *
 * Copyright(c) 2000-2012 LOCKON CO.,LTD. All Rights Reserved.
 *
 * http://www.lockon.co.jp/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

// {{{ requires
require_once CLASS_EX_REALDIR . 'page_extends/LC_Page_Ex.php';

/**
 * 会員登録のページクラス.
 *
 * @package Page
 * @author LOCKON CO.,LTD.
 * @version $Id: LC_Page_Regist.php 21950 2012-07-02 11:42:51Z pineray $
 */
class LC_Page_Conference extends LC_Page_Ex {

    // {{{ properties

    // }}}
    // {{{ functions

    /**
     * Page を初期化する.
     *
     * @return void
     */
    function init() {

        parent::init();
         $this->linkCss[] = 'css/sapaImport.css';
		 //引入本页面javascript
		 $this->link_javascript[] = "js/sapa/jquery.dataTables.js";
		 $this->htmlErrMsg ="";


    }

    /**
     * Page のプロセス.
     *
     * @return void
     */
    function process() {
        parent::process();
        $this->action();
        $this->sendResponse();

    }

    /**
     * Page のAction.
     *
     * @return void
     */
    function action() {

        switch ($this->getMode()) {
        	case 'showConference':
        		$this->tpl_mainpage = 'conference/conference_show.tpl';
        		$this->getConferenceDetail();

        		break;

            case 'editConference':
            	$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);

            	$this->tpl_mainpage = 'conference/conference_edit.tpl';
		        $this->linkCss[] = 'css/datepickerImport.css';
		        $this->link_javascript[] = "js/sapa/jquery.ui.core.js";
		        $this->link_javascript[] = "js/sapa/jquery.ui.datepicker.js";
		        $this->link_javascript[] = "js/sapa/jquery.ui.widget.js";

		        $this->getConferenceDetail();

                break;

            case 'updateConference':
            	$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
            	$this->updateConference();
            	//header("Location: ".HTTP_URL."conference/index.php");
            	SC_Response_Ex::sendRedirect(HTTP_URL."conference/index.php");
                break;

			case 'deleteConference':
            	$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
            	$this->deleteConference();
            	//header("Location: ".HTTP_URL."conference/index.php");
            	SC_Response_Ex::sendRedirect(HTTP_URL."conference/index.php");
                break;

			case 'activeConference':
            	$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
            	$this->activeConference();
            	//header("Location: ".HTTP_URL."conference/index.php");
            	SC_Response_Ex::sendRedirect(HTTP_URL."conference/index.php");
                break;

            case 'join':
            	GC_Utils::gfPrintLog("-- ".$this->objSess->GetSession('cert'));
            	GC_Utils::gfPrintLog("-- ".CERT_STRING);
		        //权限验证
		       if( $this->objSess->GetSession('cert') != CERT_STRING){
		       		SC_Response_Ex::sendRedirect(HTTP_URL."regist/login.php?mode=loginWarning");
		       		
		       }else {
		       		//大会报名
                    $conferenceId = $this->getValFromPostOrGet('conferenceId');
			        if(isset($conferenceId )){
			        	$this->getSeverceInfo();
			        	$this->tpl_mainpage ='conference/conference_join.tpl';
			       		$this->linkCss[] = 'css/datepickerImport.css';
				        $this->link_javascript[] = "js/sapa/jquery.ui.core.js";
				        $this->link_javascript[] = "js/sapa/jquery.ui.datepicker.js";
				        $this->link_javascript[] = "js/sapa/jquery.ui.widget.js";

			        }else{
			        	SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'Error,The Conference Id is missing.');
			        }
		       }
                break;
            case 'joinConference':
            		 //权限验证
		       if( $this->objSess->GetSession('cert') != CERT_STRING){

		       		SC_Response_Ex::sendRedirect(HTTP_URL."regist/login.php?mode=loginWarning");
		       }else {
		       		//serviceInfo
		       		//$orderIndexArr = $this->getValFromPostOrGet('orderIndex');
					
					$orderIndexArr =array();
		       		$serviceNameArr = $this->getValFromPostOrGet('serviceName');
		       		$priceArr = $this->getValFromPostOrGet('price');
		       		$quantityArr = $this->getValFromPostOrGet('quantity');
		       		$feeIdArr = $this->getValFromPostOrGet('feeId');


					foreach($quantityArr as $key => $value){
						if(!empty($value)){
							$orderIndexArr[]=$key;
						}
					}

		       		$payInfo = $this->getPayInfoArr($orderIndexArr,$serviceNameArr,$priceArr,$quantityArr,$feeIdArr);
					$checkResultArr = $this->goodsQuantityCheck($orderIndexArr,$quantityArr,$serviceNameArr);
		       		if($payInfo['result'] && $checkResultArr["isOk"] == "OK"){

						//$conferenceFeeInfo = array();
						$tempPayInfo = $payInfo['payInfo'];

						//$conferenceFeeInfo['serviceName'] = "Conference Fee";
						//$conferenceFeeInfo['price'] = $this->getValFromPostOrGet('conferenceFee');
						//$conferenceFeeInfo['quantity'] = 1;
						//$conferenceFeeInfo['feeId'] = "CF";

						//$conferenceFeeInfo['feeId'] = $this->getValFromPostOrGet('serviceName');
						//array_unshift($tempPayInfo,$conferenceFeeInfo);

		       			$this->putPayInfoToSession($tempPayInfo);
		       			$this->objSess->SetSession('joinInfoArr', $this->getParticipantInfoArr());
		       			$this->objSess->SetSession('payMode', 'conferencePay');
		       			$this->objSess->SetSession('joinConferenceId',$this->getValFromPostOrGet('conferenceId'));
		       			SC_Response_Ex::sendRedirect(HTTP_URL."pay/index.php?mode=payInfoConfirm");
		       		}else{
		       			$this->tpl_mainpage ='conference/conference_join.tpl';
			       		$this->linkCss[] = 'css/datepickerImport.css';
				        $this->link_javascript[] = "js/sapa/jquery.ui.core.js";
				        $this->link_javascript[] = "js/sapa/jquery.ui.datepicker.js";
				        $this->link_javascript[] = "js/sapa/jquery.ui.widget.js";
						
				        $this->makeServiceInfoFromPost($serviceNameArr,$priceArr,$quantityArr,$feeIdArr);

				        $this->htmlErrMsg = '<div class="messages error">';
						$this->htmlErrMsg .= '	<ul>';
						$this->htmlErrMsg .= '		<li>';
						$this->htmlErrMsg .= $payInfo['errMsg'];
						$this->htmlErrMsg .= '		</li>';
						$this->htmlErrMsg .= $checkResultArr["msg"];
						$this->htmlErrMsg .= '	</ul>';
						$this->htmlErrMsg .= '</div>';
		       		}
		        }

            	break;
            //会议参加者一览
            case 'showParticipant':
            	$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
        		$this->tpl_mainpage = 'conference/participant_list.tpl';
        		$this->getParticipantListInfo();

        		break;
        	//会议参加者详细信息
			case 'participantDetaiInfo':
				$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
        		$this->tpl_mainpage = 'conference/participantDetai_show.tpl';
        		$this->getparticipantDetaiInfo();

        		break;
        	//总预约商品一览
        	case 'showServiceCountDetail':
        		$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
        		$this->tpl_mainpage = 'conference/serviceCountDetail_show.tpl';
        		$this->getServiceCountDetailInfo();

        		break;
        	case 'showBuyers':
        		$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
        		$this->tpl_mainpage = 'conference/buyers_show.tpl';
        		$this->getBuyersListInfo();
        		break;
        	case 'dataExport':

				if($this->getValFromPostOrGet("exportMode") == "conference"){
					$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
	            	$this->tpl_mainpage = 'conference/conference_list.tpl';
				    $this->initConferenceDetail();

					$this->dataExport($this->conferenceInfo,"conference");
	                break;
				}
				if($this->getValFromPostOrGet("exportMode") == "participantList"){
					$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
        			$this->tpl_mainpage = 'conference/participant_list.tpl';
        			$this->getParticipantListInfo();

					$this->dataExport($this->participantListInfo,"participantList");
	                break;
				}
        		if($this->getValFromPostOrGet("exportMode") == "serviceCountDetail"){
					$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
        			$this->tpl_mainpage = 'conference/serviceCountDetail_show.tpl';
        			$this->getServiceCountDetailInfo();

					$this->dataExport($this->serviceCountDetailInfo,"serviceCountDetail");
	                break;
				}
        		if($this->getValFromPostOrGet("exportMode") == "buyerList"){
					$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
        			$this->tpl_mainpage = 'conference/buyers_show.tpl';
        			$this->getBuyersListInfo();

					$this->dataExport($this->buyerInfoArr,"buyerList");
	                break;
				}

				break;
        	default:
        		$this->adminAuthorityCheck(AUTHORITY_CONFERENCE_ADMIN);
            	$this->tpl_mainpage = 'conference/conference_list.tpl';
			    $this->initConferenceDetail();
                break;
        }
    }


    /**
     * デストラクタ.
     *
     * @return void
     */
    function destroy() {
        parent::destroy();
    }


	function dataExport($dataArr,$exportMode){

		$csv = "";

		if(!empty($dataArr)){
			if($exportMode == "conference"){
				foreach ($dataArr as $key => $value) {
					$csv .=$value["id"]. ",";
					$csv .=$value["conference_title"]. ",";
					$csv .=$value["publisher_firstname"]." ".$value["publisher_lastname"].",";
					$csv .=$value["start_time"]. ",";
					$csv .=$value["close_time"]. ",";
					$csv .=$value["status"]. ",";
					$csv .=$value["manCount"]. ",";
					$csv .=$value["amountCount"]. "\n";

				}
				header("Content-Type: application/octet-stream");
				header("Content-Disposition: attachment; filename=ConferenceList.csv");
				//header("Content-Type: text/csv; charset=UTF-8 ");
				//echo mb_convert_encoding("テスト\n","SJIS", "UTF-8");

			}

			if($exportMode == "participantList"){
				foreach ($dataArr as $key => $value) {
					$csv .=$value["participant_lastname"]." ".$value["participant_firstname"].",";
					$csv .=$value["mail_add"]. ",";
					$csv .=$value["tel_no"]. ",";
					$csv .=$value["fax_no"]. ",";
					$csv .=$value["start_date"]. ",";
					$csv .=$value["end_date"]. ",";
					$csv .=$value["sumAmount"]. "\n";
				}
				header("Content-Type: application/octet-stream");
				header("Content-Disposition: attachment; filename=participantInfo.csv");
				//header("Content-Type: text/csv; charset=UTF-8 ");
				//echo mb_convert_encoding("テスト\n","SJIS", "UTF-8");
			}

			if($exportMode == "serviceCountDetail"){
				foreach ($dataArr as $key => $value) {
					$csv .=$value["fees_name"].",";
					$csv .=$value["quantity"]. ",";
					$csv .=$value["amount"]. "\n";
				}
				header("Content-Type: application/octet-stream");
				header("Content-Disposition: attachment; filename=serviceCountDetail.csv");
			}

			if($exportMode == "buyerList"){
				foreach ($dataArr as $key => $value) {
					$csv .=$value["name"].",";
					$csv .=$value["quantity"]. ",";
					$csv .=$value["amount"]. "\n";
				}
				header("Content-Type: application/octet-stream");
				header("Content-Disposition: attachment; filename=buyerList.csv");
			}
		}
		echo($csv);
		exit();
	}

    function initConferenceDetail(){
    		$objQuery = SC_Query::getSingletonInstance();
		    $this->conferenceInfo = $objQuery->select('*','mst_conference');


		    foreach ($this->conferenceInfo as $key => $value) {

		    	////同一个会议里同一个人报名多次  当一个人统计
		    	$manCount = $objQuery->select('*','tab_conference_participant', "conference_id = ? group by conference_id,user_id", array($value['id']));
		    	$this->conferenceInfo[$key]['manCount'] = count($manCount);

		    	$objQuery->setGroupBy("goods_type");
		    	$conferenceId = "CF".str_pad($value["id"],8,"*",STR_PAD_LEFT);
		    	$amountCount = $objQuery->select('sum(amount) as amount','tab_pay_detail',"goods_type=? ",array($conferenceId));
				if(empty($amountCount[0]['amount'])){
					$amountCount[0]['amount'] = 0;
				}
		    	$this->conferenceInfo[$key]['amountCount'] = $amountCount[0]['amount'];
		    	$objQuery->setGroupBy("");


		    	//已删除
		    	if($value['del_flg'] == '1'){
		    		$this->conferenceInfo[$key]['status'] ='Deleted';
					$this->conferenceInfo[$key]['canBeEdit'] = "Deleted";
		    	//已锁定
		    	}elseif ($value['status'] != '0'){
		    		$this->conferenceInfo[$key]['status'] ='Blocked';
					$this->conferenceInfo[$key]['canBeEdit']  = "Blocked";
		    	}else{
		    		$now = date('Y-m-d H:i:s');
		    		//未开始
		    		if (strtotime($now) < strtotime($value['start_time'])) {
		    			$this->conferenceInfo[$key]['status'] ='In preparation';

		    		//进行中
		    		}elseif (strtotime($now) >= strtotime($value['start_time'])
		    				&& strtotime($now) <= strtotime($value['close_time'])){
		    			$this->conferenceInfo[$key]['status'] ='In progress';

		    		//已结束
		    		}else {
		    			$this->conferenceInfo[$key]['status'] ='Ended';

		    		}
		    	}
		    }
    }

    function getConferenceDetail(){

    	 $id=$this->getValFromPostOrGet('id');

    	 if(isset($id)){
	    	$objQuery = SC_Query::getSingletonInstance();
			$conferenceInfo = $objQuery->select('*','mst_conference','id = ?',array($id));

			$this->conferenceInfo['id'] = $conferenceInfo[0]['id'];
	    	$this->conferenceInfo['conferenceName'] = $conferenceInfo[0]['conference_title'];
	    	$this->conferenceInfo['from'] = $conferenceInfo[0]['start_time'];
	    	$this->conferenceInfo['to'] = $conferenceInfo[0]['close_time'];
	    	$this->conferenceInfo['venue'] = $conferenceInfo[0]['conference_place'];
	    	$this->conferenceInfo['summary'] = $conferenceInfo[0]['contents'];
	    	$this->conferenceInfo['organizer'] = $conferenceInfo[0]['organizer'];
	    	$this->conferenceInfo['tel'] = $conferenceInfo[0]['conference_tel'];
	    	$this->conferenceInfo['fax'] = $conferenceInfo[0]['conference_fax'];

			//$attachment = split("_",$conferenceInfo[0]['conference_file']);
			$attachment = substr($conferenceInfo[0]['conference_file'],15);
	    	$this->conferenceInfo['attachment'] = $attachment;
	    	$this->conferenceInfo['downloadfile'] = CONFERENCE_UP_URLPATH.$conferenceInfo[0]['conference_file'];

	    	$this->conferenceInfo['headcountLimit'] = $conferenceInfo[0]['persons_limite'];
	    	$this->conferenceInfo['freeMembersFee'] = $conferenceInfo[0]['free_members_fee'];
	    	$this->conferenceInfo['membersFee'] = $conferenceInfo[0]['members_fee'];
	    	$this->conferenceInfo['freeStudentMembersFee'] = $conferenceInfo[0]['free_student_members_fee'];

	    	$this->conferenceInfo['from'] = date('Y-m-d',strtotime($this->conferenceInfo['from']));
	    	$this->conferenceInfo['to'] = date('Y-m-d',strtotime($this->conferenceInfo['to']));


	    	$this->conferenceFeeInfo = $objQuery->select('*','tab_conference_fee','conference_id = ? and del_flg = 0 ',array($id));
	    	//$totalArr = $objQuery->select('sum(body_total)','tab_conference_participant','conference_id = ?',array($id));
			$selectId = PAYINFO_INS_STR.$id;
			$selectId = "SF".str_pad($selectId,8,"*",STR_PAD_LEFT);
	    	$totalArr = $objQuery->select("SUM(quantity) as sm",'tab_pay_detail','goods_id = ?',array($selectId));
	    	
	    	foreach ($this->conferenceFeeInfo as $index=>$value){

	    		$goodsId = "SF".str_pad($value['id'],8,"*",STR_PAD_LEFT);
	    		$cntArr = $objQuery->select("SUM(quantity) as sm",'tab_pay_detail','goods_id = ?  ',array($goodsId));
	    		$cnt = $cntArr[0]["sm"];
	    		if(empty($cnt)) {$cnt = 0;}
	    		$this->conferenceFeeInfo[$index]['goodsCount'] = $cnt;
	    	}

			$this->total = $totalArr[0]['sm'];
			if(empty($this->total)){
				$this->total = 0;
			}
			if($this->total < $conferenceInfo[0]['persons_limite']){
					$this->canJoinFlg = "OK";
			}else{
				    $this->canJoinFlg = "NG";
			}

	    	$this->serviceCount = count($this->conferenceFeeInfo);
    	}else{
    		SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'system error please contact the administrator.');
    	}
    }


	function updateConference(){
		$id= $this->getValFromPostOrGet('conferenceId');
		if(isset($id)){
			$updateArr = array();
	    	//$updateArr['publisher_id'] = $this->objSess->getSession('user_id');				//发布者ID
			//$updateArr['publisher_lastname'] = $this->objSess->getSession('lastname');      	//发布者（姓）
			//$updateArr['publisher_firstname'] = $this->objSess->getSession('firstname');     	//发布者（名）
			$updateArr['conference_title'] =  $this->getValFromPostOrGet('conferenceName');     //会议名称
			$updateArr['contents'] = $this->getValFromPostOrGet('summary');                		//会议概要
			$updateArr['organizer'] = $this->getValFromPostOrGet('organizer');               	//会议组织方名
			$updateArr['persons_limite'] = $this->getValFromPostOrGet('headcountLimit');        //人数上限
			$updateArr['conference_place'] = $this->getValFromPostOrGet('venue');        		//举办地
			$updateArr['conference_tel'] = $this->getValFromPostOrGet('tel');          			//大会联络电话
			$updateArr['conference_fax'] = $this->getValFromPostOrGet('fax');          			//大会FAX
			$updateArr['start_time'] = $this->getValFromPostOrGet('from');              		//举办时间
			$updateArr['close_time'] = $this->getValFromPostOrGet('to');              			//结束时间

			//$updateArr['status'] = '0';                  										//大会状态 0： 正常 1： 临时取消
			$updateFileName = $this->getUploadFile();
			if(!empty($updateFileName)){
				$updateArr['conference_file'] = $updateFileName;        					//会议附件
			}
			$updateArr['members_fee'] = $this->getValFromPostOrGet('membersFee'); 
			$updateArr['free_members_fee'] = $this->getValFromPostOrGet('freeMembersFee'); 
			$updateArr['free_student_members_fee'] = $this->getValFromPostOrGet('freeStudentMembersFee'); 
			
			$updateArr['del_flg'] = '0';
			$updateArr['create_time'] = 'now()';
			$updateArr['update_time'] = 'now()';

			$objQuery = SC_Query::getSingletonInstance();
			$objQuery->begin();

			$objQuery->update('mst_conference', $updateArr, "id = ?", array($id));

			//删除该会议的所有付费项目
			//$objQuery->delete('tab_conference_fee', 'conference_id = ?',array($id));
			//插入修改后的付费项目
			//$insertFeeArr = $this->getInsertFeeArr($id);

			//if(count($insertFeeArr)>0){
			//	foreach ($insertFeeArr as $value) {
			//		$objQuery->insert('tab_conference_fee', $value);
			//	}
			//}
			$checkFeeIdArr = $this->getValFromPostOrGet('checkFeeId');
			$feeIdArr = $this->getValFromPostOrGet('feeId');
			
			$checkServiceNameArr = $this->getValFromPostOrGet('checkServiceName');
			$serviceNameArr = $this->getValFromPostOrGet('serviceName');
			
			$checkMembersPriceArr = $this->getValFromPostOrGet('checkMembersPrice');
			$membersPriceArr = $this->getValFromPostOrGet('membersPrice');
			
			$checkFreeMembersPriceArr = $this->getValFromPostOrGet('checkFreeMembersPrice');
			$freeMembersPriceArr = $this->getValFromPostOrGet('freeMembersPrice');
			
			$checkFreeStudentMembersPriceArr = $this->getValFromPostOrGet('heckFreeStudentMembersPrice');
			$freeStudentMembersPriceArr = $this->getValFromPostOrGet('freeStudentMembersPrice');
			
			$checkLimitArr = $this->getValFromPostOrGet('checkLimit');
			$limitArr = $this->getValFromPostOrGet('limit');
			
			//被更新和被删除的数据处理
			foreach ($checkFeeIdArr as $key => $value) {
						
				if(in_array($value,$feeIdArr)){
					// change happaned
					if($checkServiceNameArr[$key] != $serviceNameArr[$key] 
						||$checkMembersPriceArr[$key] != $membersPriceArr[$key]
						||$checkFreeMembersPriceArr[$key] != $freeMembersPriceArr[$key]
						||$checkLimitArr[$key] != $limitArr[$key]
						||$checkFreeStudentMembersPriceArr[$key] != $freeStudentMembersPriceArr[$key]){
							
						$updatetempArr = array();
					 	$updatetempArr['fees_name'] = $serviceNameArr[$key];
					 	$updatetempArr['member_price'] = $membersPriceArr[$key];
					 	$updatetempArr['free_member_price'] = $freeMembersPriceArr[$key];
					 	$updatetempArr['free_student_price'] = $freeStudentMembersPriceArr[$key];
					 	$updatetempArr['head_limit'] = $limitArr[$key];
					 	
					 	$objQuery->update("tab_conference_fee", $updatetempArr," id = ?",array($value));	
					}
				}else{
				 //delete
				 $updatetempArr = array();
				 $updatetempArr['del_flg'] = "1";
				 $objQuery->update("tab_conference_fee", $updatetempArr,"id = ?",array($value));
				}
			}
			//新加的服务项目插入数据库
			foreach ($feeIdArr as $key => $value) {
				if( !in_array($value,$checkFeeIdArr) && $value ="addServiceIdFlg" ){
					 $objQuery->insert("tab_conference_fee", $this->getInsertFeeArr($id,$serviceNameArr[$key],$membersPriceArr[$key],$freeMembersPriceArr[$key],$freeStudentMembersPriceArr[$key],$limitArr[$key]));
				}
			}
			//操作数据库出错
    		if ($objQuery->isError()){
    			$objQuery->rollback();
    			SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, "Update DB error,please contact with administrator");
    			exit();
    		}else{
    			$objQuery->commit();
    		}

		}else{
			SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'system error please contact the administrator.');
		}
    }

	function getInsertFeeArr($conferenceId,$serviceName,$membersPrice,$freeMembersPrice,$freeStudentMembersPrice,$limit){
    	$rsArr = array();

		//$rs['id'] = '';//项目ID		id
		$rsArr['conference_id'] = $conferenceId;	//会议ID
		$rsArr['fees_name'] = $serviceName;	//项目名
		$rsArr['member_price'] = $membersPrice;	//价格
		$rsArr['free_member_price'] = $freeMembersPrice;	//价格
		$rsArr['free_student_price'] = $freeStudentMembersPrice;	//价格
		$rsArr['head_limit'] = $limit;	//价格
		$rsArr['unit'] = '';	//单位
		$rsArr['del_flg'] = '0';	//削除フラグ
		$rsArr['create_time'] = 'now()';	//作成日時
		$rsArr['update_time'] = 'now()';	//更新日時

    	return $rsArr;
    }

    function getSeverceInfo(){
		$id = $this->getValFromPostOrGet('conferenceId');
		$this->showConferenceId = $id;
		$objQuery = SC_Query::getSingletonInstance();
		$this->serviceInfo = $objQuery->select('*','tab_conference_fee','conference_id = ? and del_flg = 0',array($id));

		$inputInfo = array();

    	$inputInfo['lastName'] = $this->objSess->GetSession("lastname");
    	$inputInfo['firstName'] = $this->objSess->GetSession("firstname");
    	$inputInfo['email'] = $this->objSess->GetSession("user_email");
    	$inputInfo['tel'] = $this->objSess->GetSession("tel");
    	$inputInfo['fax'] = $this->objSess->GetSession("fax");

    	$this->inputInfoArr = $inputInfo;

    	$tempInputInfo = array();
    	$userType = $this->objSess->GetSession("memberFlg");

		if(!empty($userType)){

			$tempInputInfo['fees_name'] = "Conference Fee";
			//
			if($userType == NONE_MEMBER || $userType == NONE_MEMBER_CORPORATION){
				$tempInputInfo['price'] = $this->getValFromPostOrGet("freeMembersFee");
			}else if($userType == NONE_MEMBER_STUDENT){
				$tempInputInfo['price'] = $this->getValFromPostOrGet("freeStudentMembersFee");
			}else {
				$tempInputInfo['price'] = $this->getValFromPostOrGet("membersFee");
			}
			$tempInputInfo['fees_name'] = "Conference Fee";
			$tempInputInfo['head_limit'] = $this->getValFromPostOrGet("headcountLimit");
			$tempInputInfo['total'] = $this->getValFromPostOrGet("total");
			$tempInputInfo['id'] = PAYINFO_INS_STR.$id;

			//
			foreach ($this->serviceInfo as $key => $value) {

				if($userType == NONE_MEMBER || $userType == NONE_MEMBER_CORPORATION){
					$this->serviceInfo[$key]['price'] = $this->serviceInfo[$key]['free_member_price'];
				}else if($userType == NONE_MEMBER_STUDENT){
					$this->serviceInfo[$key]['price'] = $this->serviceInfo[$key]['free_student_price'];
				}else {
					$this->serviceInfo[$key]['price'] = $this->serviceInfo[$key]["member_price"];
				}

				$valArr = array();
				$goodsId= "SF".str_pad($value['id'],8,"*",STR_PAD_LEFT);
				 
				$cnt = $objQuery->count('tab_pay_detail','goods_id = ?  and del_flg = 0',array($goodsId));
				$this->serviceInfo[$key]['total'] = $cnt;
			}
		}else {
			SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'session  error. user type is null.');

		}

        array_unshift($this->serviceInfo,$tempInputInfo);
    }

    function makeServiceInfoFromPost($serviceNameArr,$priceArr,$quantityArr,$feeIdArr){

    	$headcountLimitArr = $this->getValFromPostOrGet('headcountLimit');
		$totalArr = $this->getValFromPostOrGet('total');
    	
		foreach ($serviceNameArr as $index=>$val) {
    		$serviceInfoArr = array();
    		$serviceInfoArr['fees_name'] =  $val;
    		$serviceInfoArr['price'] =  $priceArr[$index];
    		$serviceInfoArr['quantity'] =  $quantityArr[$index];
    		$serviceInfoArr['id'] = $feeIdArr[$index];
    		$serviceInfoArr['total'] = $totalArr[$index];
    		$serviceInfoArr['head_limit'] = $headcountLimitArr[$index];

    		$this->serviceInfo[] = $serviceInfoArr;
    	}
    	$info = array();
	    $info['lastName'] = $this->getValFromPostOrGet("lastName");
	    $info['firstName'] = $this->getValFromPostOrGet("firstName");
	    $info['email'] = $this->getValFromPostOrGet("email");
	    $info['tel'] = $this->getValFromPostOrGet("tel");
	    $info['fax'] = $this->getValFromPostOrGet("fax");
	    $info['partners'] = $this->getValFromPostOrGet("partners");
	    $info['partnersNames'] = $this->getValFromPostOrGet("partnersNames");
	    $info['from'] = $this->getValFromPostOrGet("from");
	    $info['to'] = $this->getValFromPostOrGet("to");
		$info['conferenceFee'] = $this->getValFromPostOrGet("conferenceFee");

    	$this->inputInfoArr = $info;
    	$this->showConferenceId = $this->getValFromPostOrGet("conferenceId");
    }
    function getParticipantInfoArr(){

    	$participantInfo = array();
    	$participantInfo['conference_id'] = $this->getValFromPostOrGet('conferenceId');
		$participantInfo['user_id'] = $this->objSess->GetSession('user_id');
		$participantInfo['participant_lastname'] = $this->getValFromPostOrGet('lastName');
		$participantInfo['participant_firstname'] = $this->getValFromPostOrGet('firstName');
		$participantInfo['tel_no'] = $this->getValFromPostOrGet('tel');
		$participantInfo['fax_no'] = $this->getValFromPostOrGet('fax');
		$participantInfo['mail_add'] = $this->getValFromPostOrGet('email');
		$participantInfo['body_total'] = $this->getValFromPostOrGet('partners');
		$participantInfo['person_names'] = $this->getValFromPostOrGet('partnersNames');
		$participantInfo['start_date'] = $this->getValFromPostOrGet('from');
		$participantInfo['end_date'] = $this->getValFromPostOrGet('to');
		$participantInfo['message'] = $this->getValFromPostOrGet('partnersNames');
		$participantInfo['del_flg'] = "0";
		$participantInfo['create_time'] = "now()";
		$participantInfo['update_time'] = "now()";

		return $participantInfo;
    }

    function getParticipantListInfo(){

    	$conferenceId = $this->getValFromPostOrGet("conferenceId");
    	$this->dateExportUseConfId =$conferenceId;

    	if(!empty($conferenceId)){
	    	$objQuery = SC_Query::getSingletonInstance();
	    	//同一个会议里同一个人报名多次  当一个人统计
			$this->participantListInfo = $objQuery->select('*','tab_conference_participant','conference_id = ? and del_flg = 0 GROUP BY conference_id  ,user_id',array($conferenceId));

			foreach ($this->participantListInfo as $index=> $value) {
				$valArr = array();
				$goodsType= "CF".str_pad($value['conference_id'],8,"*",STR_PAD_LEFT);
				$userId = $value['user_id'];

				$rs = $objQuery->select('goods_type,sum(amount)','tab_pay_detail','goods_type = ? and user_id = ? and del_flg = 0',array($goodsType,$userId));
				$this->participantListInfo[$index]['sumAmount'] = $rs[0]['sum(amount)'];
				$this->participantListInfo[$index]['conferenceId'] = $conferenceId;
			}
    	}
    }

    function getparticipantDetaiInfo(){

    	$userId = $this->getValFromPostOrGet("userId");
    	$conferenceId = $this->getValFromPostOrGet("conferenceId");

    	$objQuery = SC_Query::getSingletonInstance();
		$participantDetaiInfo = $objQuery->select('*','tab_conference_participant','conference_id = ? and user_id = ? and del_flg = 0',array($conferenceId,$userId));
		$this->participantInfoArr = $participantDetaiInfo[0];

		$goodsType= "CF".str_pad($conferenceId,8,"*",STR_PAD_LEFT);
		$this->serviceInfo = $objQuery->select("*","tab_pay_detail","goods_type = ? and user_id = ? ",array($goodsType,$userId));

		foreach ($this->serviceInfo as $key=>$value) {
			//是会费的时候
			 if (strstr($value['goods_id'], PAYINFO_INS_STR)) {
			 	$tempid = substr($value['goods_type'], 2);
				$tempid = str_replace("*","",$tempid);
				$tempRs = $objQuery->select("conference_title","mst_conference","id = ?" ,array($tempid));
				$this->serviceInfo[$key]['fees_name'] = $tempRs[0]['conference_title']; 	
			 }else{
				$tempid = substr($value['goods_id'], 2);
				$tempid = str_replace("*","",$tempid);
				$tempRs = $objQuery->select("fees_name","tab_conference_fee","id = ?" ,array($tempid));
				$this->serviceInfo[$key]['fees_name'] = $tempRs[0]['fees_name']; 	
			 }
		}
		$conferenceId = $this->getValFromPostOrGet("conferenceId");
    }

    function getServiceCountDetailInfo(){
    	$id = $this->getValFromPostOrGet("conferenceId");
    	$conferenceId= "CF".str_pad($id,8,"*",STR_PAD_LEFT);

    	$this->dateExportUseConfId = $id;
    	$objQuery = SC_Query::getSingletonInstance();
    	$objQuery->setGroupBy("goods_id");
    	$this->serviceCountDetailInfo = $objQuery->select("goods_id ,goods_type,SUM(quantity) as quantity,SUM(amount) as amount","tab_pay_detail","goods_type = ? ",array($conferenceId));
    	$objQuery->setGroupBy("");

    	foreach ($this->serviceCountDetailInfo as  $index =>$value) {
			if(strstr($value['goods_id'], PAYINFO_INS_STR)){
				$tempid = substr($value['goods_type'], 2);
				$tempid = str_replace("*","",$tempid);
				$tempRs = $objQuery->select("conference_title","mst_conference","id = ?" ,array($tempid));
				$this->serviceCountDetailInfo[$index]['fees_name'] = $tempRs[0]['conference_title'];
				$this->serviceCountDetailInfo[$index]['feeId'] = "conferenceFee";	
			}else{
				$tempid = substr($value['goods_id'], 2);
				$tempid = str_replace("*","",$tempid);
				$tempRs = $objQuery->select("fees_name,id","tab_conference_fee","id = ?" ,array($tempid));
				$this->serviceCountDetailInfo[$index]['fees_name'] = $tempRs[0]['fees_name'];
				$this->serviceCountDetailInfo[$index]['feeId'] = $tempRs[0]['id'];	
			}
    		
    	}


    }

    function getBuyersListInfo(){
    	$goodsId = $this->getValFromPostOrGet("feeId");
    	$goodsId= "SF".str_pad($goodsId,8,"*",STR_PAD_LEFT);

    	$this->dateExportUseFeeId = $this->getValFromPostOrGet("feeId");
    	$objQuery = SC_Query::getSingletonInstance();
    	$objQuery->setGroupBy("user_id ,goods_id");
    	$this->buyerInfoArr = $objQuery->select("user_id ,SUM(quantity)  as quantity,SUM(amount) as amount","tab_pay_detail","goods_id = ? ",array($goodsId));
    	$objQuery->setGroupBy("");

    	foreach ($this->buyerInfoArr as $index => $value) {

    		$tempRs = $objQuery->select("lastname ,firstname","tab_person_users","id = ? ",array($value['user_id']));
    		$this->buyerInfoArr[$index]['name'] = $tempRs[0]['lastname']." ". $tempRs[0]['firstname'];
    	}

    }

	function deleteConference(){
		$id= $this->getValFromPostOrGet('conferenceId');
		if(isset($id)){
			$updateArr = array();
	    	//$updateArr['publisher_id'] = $this->objSess->getSession('user_id');			//发布者ID
			//$updateArr['publisher_lastname'] = $this->objSess->getSession('lastname');      //发布者（姓）
			//$updateArr['publisher_firstname'] = $this->objSess->getSession('firstname');     //发布者（名）
			//$updateArr['conference_title'] =  $this->getValFromPostOrGet('conferenceName');        //会议名称
			//$updateArr['contents'] = $this->getValFromPostOrGet('summary');                //会议概要
			//$updateArr['organizer'] = $this->getValFromPostOrGet('organizer');               //会议组织方名
			//$updateArr['persons_limite'] = $this->getValFromPostOrGet('headcountLimit');          //人数上限
			//$updateArr['conference_place'] = $this->getValFromPostOrGet('venue');        //举办地
			//$updateArr['conference_tel'] = $this->getValFromPostOrGet('tel');          //大会联络电话
			//$updateArr['conference_fax'] = $this->getValFromPostOrGet('fax');          //大会FAX
			//$updateArr['start_time'] = $this->getValFromPostOrGet('from');              //举办时间
			//$updateArr['close_time'] = $this->getValFromPostOrGet('to');              //结束时间
			//$updateArr['conference_file'] = $this->getValFromPostOrGet('attachment');         //会议附件
			//$updateArr['status'] = '0';                  //大会状态 0： 正常 1： 临时取消

			$updateArr['del_flg'] = '1';
			//$updateArr['create_time'] = 'now()';
			//$updateArr['update_time'] = 'now()';

			$objQuery = SC_Query::getSingletonInstance();
			$objQuery->begin();

			$objQuery->update('mst_conference', $updateArr, "id = ?", array($id));
			//删除该会议的所有付费项目
			//$objQuery->delete('tab_conference_fee', 'conference_id = ?',array($id));
			//插入修改后的付费项目
			//$insertFeeArr = $this->getInsertFeeArr($id);
			//
			//if(count($insertFeeArr)>0){
			//	foreach ($insertFeeArr as $value) {
			//		$objQuery->insert('tab_conference_fee', $value);
			//	}
			//}

			//操作数据库出错
    		if ($objQuery->isError()){
    			$objQuery->rollback();
    			SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, "Update DB error,please contact with administrator");
    			exit();
    		}else{
    			$objQuery->commit();
    		}

		}else{
			SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'system error please contact the administrator.');
		}
    }


	function activeConference(){
		$id= $this->getValFromPostOrGet('conferenceId');
		if(isset($id)){
			$updateArr = array();
	    	//$updateArr['publisher_id'] = $this->objSess->getSession('user_id');			//发布者ID
			//$updateArr['publisher_lastname'] = $this->objSess->getSession('lastname');      //发布者（姓）
			//$updateArr['publisher_firstname'] = $this->objSess->getSession('firstname');     //发布者（名）
			//$updateArr['conference_title'] =  $this->getValFromPostOrGet('conferenceName');        //会议名称
			//$updateArr['contents'] = $this->getValFromPostOrGet('summary');                //会议概要
			//$updateArr['organizer'] = $this->getValFromPostOrGet('organizer');               //会议组织方名
			//$updateArr['persons_limite'] = $this->getValFromPostOrGet('headcountLimit');          //人数上限
			//$updateArr['conference_place'] = $this->getValFromPostOrGet('venue');        //举办地
			//$updateArr['conference_tel'] = $this->getValFromPostOrGet('tel');          //大会联络电话
			//$updateArr['conference_fax'] = $this->getValFromPostOrGet('fax');          //大会FAX
			//$updateArr['start_time'] = $this->getValFromPostOrGet('from');              //举办时间
			//$updateArr['close_time'] = $this->getValFromPostOrGet('to');              //结束时间
			//$updateArr['conference_file'] = $this->getValFromPostOrGet('attachment');         //会议附件
			//$updateArr['status'] = '0';                  //大会状态 0： 正常 1： 临时取消

			$updateArr['del_flg'] = '0';
			//$updateArr['create_time'] = 'now()';
			//$updateArr['update_time'] = 'now()';

			$objQuery = SC_Query::getSingletonInstance();
			$objQuery->begin();

			$objQuery->update('mst_conference', $updateArr, "id = ?", array($id));
			//删除该会议的所有付费项目
			//$objQuery->delete('tab_conference_fee', 'conference_id = ?',array($id));
			//插入修改后的付费项目
			//$insertFeeArr = $this->getInsertFeeArr($id);
			//
			//if(count($insertFeeArr)>0){
			//	foreach ($insertFeeArr as $value) {
			//		$objQuery->insert('tab_conference_fee', $value);
			//	}
			//}

			//操作数据库出错
    		if ($objQuery->isError()){
    			$objQuery->rollback();
    			SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, "Update DB error,please contact with administrator");
    			exit();
    		}else{
    			$objQuery->commit();
    		}

		}else{
			SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'system error please contact the administrator.');
		}
    }

    function  getUploadFile(){

    	$fileName = $_FILES["attachment"]["name"] ;

    	if(!empty($fileName)){

	    	if ($_FILES["attachment"]["size"] > CONFERENCE_UP_MAX_SIZE )
	    	{
	    		$this->htmlErrMsg  = '<div class="messages error">';
	    		$this->htmlErrMsg .= '	<ul>';
	    		$this->htmlErrMsg .= '		<li>upload file is too big '.$_FILES["attachment"]["size"].'</li>';
	    		$this->htmlErrMsg .= '		<li>please smaller than '.(CONFERENCE_UP_MAX_SIZE/1024).'M</li>';
	    		$this->htmlErrMsg .= ' 	</ul>';
	    		$this->htmlErrMsg .= '</div>';

	    		$this->tpl_mainpage = 'conference/create_conference.tpl';
	    	}else{
	    		$fileName = $_FILES["attachment"]["name"] ;
	    		$fileTmpName = $_FILES["attachment"]["tmp_name"];
	    		$this->conferenceInfo['attachment'] = $_FILES["attachment"]["name"];

	    		$date = new DateTime();
	    		$fileName = $date->format('YmdHis')."_".$fileName;
	    		$this->conferenceInfo['savedFileName'] = $fileName;

	    		move_uploaded_file($fileTmpName,CONFERENCE_UP_REALDIR.$fileName);
	    	}
    	}

    	return $fileName;
    }
	function goodsQuantityCheck($orderIndexArr,$quantityArr,$serviceNameArr){
		
		$returnArr = array();
		$result = "OK";
		$msgStr = "";
		
		$headcountLimitArr = $this->getValFromPostOrGet('headcountLimit');
		$feeIdlArr = $this->getValFromPostOrGet('feeId');
		
		$objQuery = SC_Query::getSingletonInstance();
		foreach ($orderIndexArr as $value) {
			$tempid = "SF".str_pad($feeIdlArr[$value],8,"*",STR_PAD_LEFT);
			$tempCount = $objQuery->count("tab_pay_detail","goods_id = ?" ,array($tempid));
			$tempCount += $quantityArr[$value];
			if($tempCount > $headcountLimitArr[$value] ){
				$result = "NG";
				$msgStr.= "<li>".$serviceNameArr[$value]." Inventory shortage，please refresh the Screen and Re-enter the number of orders </li>";
			}
		}
		$returnArr["isOk"] = $result;
		$returnArr["msg"] = $msgStr;
		return $returnArr;
	}
}
